import dictService from "@/api/services/system/dictService";
import ColorPickerFormItem from "@/components/form/ColorPickerFormItem";
import { useDictionaryStore } from "@/store/useDictionaryStore";
import { Button, ColorPicker, Drawer, Flex, Form, Input, InputNumber, Modal, Select, Table, Tooltip, message } from "antd";
import { useEffect, useState } from "react";
import type { Dict, DictItem } from "#/entity";
import { BasicStatus } from "#/enum";
import { useCopyToClipboard } from "@/hooks";

import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { docco } from "react-syntax-highlighter/dist/cjs/styles/hljs";
import IconButton from "@/components/icon/icon-button";
import { LucideIcon } from "@/components/icon";
// import { solarizedLight } from 'react-syntax-highlighter/dist/cjs/styles/hljs';

interface DictItemPro {
	open: boolean;
	onClose: () => void;
	dict: Dict | null;
}

export default function DictItemPage({ open, onClose, dict }: DictItemPro) {
	const [loading, setLoading] = useState(false);
	const [itemList, setItemList] = useState<DictItem[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
	const [editingItem, setEditingItem] = useState<DictItem | null>(null);
	const [editVisable, setEditVisable] = useState(false);
	const [form] = Form.useForm();

	const [codeVisible, setCodeVisible] = useState(false);
	const [enumCode, setEnumCode] = useState<string>("");

	const { copyFn } = useCopyToClipboard();

	// 获取列表
	const fetchList = async () => {
		if (!dict) return; // 确保有 roleId 才执行

		setLoading(true);
		try {
			const res = await dictService.itemList(dict.id);
			setItemList(res);
		} catch (error) {
			message.error("获取字典项失败");
		} finally {
			setLoading(false);
		}
	};

	useEffect(() => {
		if (open && dict) {
			fetchList();
		}
	}, [open, dict]);

	/**
	 * 添加字典项
	 */
	const handlerAdd = () => {
		setEditVisable(true);
	};

	//删除角色方法
	const handleDelete = async () => {
		try {
			setLoading(true);
			await dictService.deleteItem(selectedRowKeys);
			message.success("删除成功");
			setSelectedRowKeys([]); // 清空选中项
			fetchList(); // 重新加载列表
		} catch (error) {
			message.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	const handleEdit = (record: DictItem) => {
		setEditingItem(record);
		form.setFieldsValue(record);
		setEditVisable(true);
	};

	const handleSubmit = async (values) => {
		try {
			setLoading(true);
			if (editingItem) {
				await dictService.updateItem({ ...values, id: editingItem.id, dictId: dict?.id, dictCode: dict?.dictCode });
				message.success("更新字典项成功");
			} else {
				await dictService.addItem({ ...values, dictId: dict?.id, dictCode: dict?.dictCode });
				message.success("创建字典项成功");
			}
			setEditVisable(false);
			setEditingItem(null);
			form.resetFields();
			fetchList();

			//刷新缓存
			if (dict) {
				useDictionaryStore.getState().refreshDictionary(dict.dictCode);
			}
		} catch (error) {
			message.error(`${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	/**
	 * 生成枚举类代码
	 */
	const generateCode = async () => {
		try {
			const res = await dictService.generateEnum(dict?.id);
			setEnumCode(res);
			setCodeVisible(true);
		} catch (error) {
			message.error(`${error.message}`);
		}
	};

	const handleCodeCancel = () => {
		setCodeVisible(false);
	};

	const itemColumns = [
		{ title: "字典项编码", dataIndex: "itemCode" },
		{ title: "字典项名称", dataIndex: "itemText" },
		{ title: "字典项键值", dataIndex: "itemValue" },
		{ title: "序号", dataIndex: "sort" },
		{
			title: "标签颜色",
			dataIndex: "color",
			render: (_, record) => <ColorPicker value={record.color} disabled />,
		},
		{
			title: "操作",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Flex gap="small" wrap>
					<Button type="link" onClick={() => handleEdit(record)}>
						编辑
					</Button>
				</Flex>
			),
		},
	];

	const handleEditClose = () => {
		setEditVisable(false);
		setEditingItem(null);
	};

	function handleCopy(event: MouseEvent<HTMLButtonElement, MouseEvent>): void {
		throw new Error("Function not implemented.");
	}

	return (
		<>
			<Drawer
				title="字典项"
				width={720}
				open={open}
				onClose={onClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={onClose}>关闭</Button>
					</div>
				}
			>
				<div className="flex gap-2">
					<Button type="primary" onClick={handlerAdd}>
						添加字典项
					</Button>
					<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
						删除
					</Button>
					<Button onClick={generateCode}>生成枚举类</Button>
				</div>
				<div className="h-4" />
				<Table
					rowKey="id"
					scroll={{ x: "max-content" }}
					loading={loading}
					pagination={false}
					rowSelection={{
						type: "checkbox",
						selectedRowKeys: selectedRowKeys,
						onChange: (selectedKeys) => {
							setSelectedRowKeys(selectedKeys as string[]);
						},
					}}
					columns={itemColumns}
					dataSource={itemList}
					size="middle"
				/>
			</Drawer>

			{/* 编辑 */}
			<Drawer
				title={editingItem ? "编辑字典项" : "新增字典项"}
				width={480}
				open={editVisable}
				onClose={handleEditClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleEditClose}>取消</Button>
						<Button type="primary" onClick={() => form.submit()}>
							确定
						</Button>
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit}>
					<Form.Item name="itemCode" label="字典项编码" rules={[{ required: true, message: "请输入字典项编码" }]}>
						<Input placeholder="请输入字典项编码" disabled={editingItem !== null}/>
					</Form.Item>
					<Form.Item name="itemText" label="字典项名称" rules={[{ required: true, message: "请输入字典项名称" }]}>
						<Input placeholder="请输入字典项名称" />
					</Form.Item>
					<Form.Item name="itemValue" label="字典项键值" rules={[{ required: true, message: "请输入字典项键值" }]}>
						<Input placeholder="请输入字典项键值" />
					</Form.Item>
					<Form.Item label="序号" name="sort">
						<InputNumber style={{ width: "100%" }} />
					</Form.Item>
					<ColorPickerFormItem label="标签颜色" name="color" rules={[{ required: true, message: "请选择颜色" }]} />
					<Form.Item name="description" label="描述">
						<Input placeholder="请输入描述" />
					</Form.Item>

					<Form.Item name="status" label="状态" initialValue={BasicStatus.ENABLE}>
						<Select
							options={[
								{ label: "启用", value: BasicStatus.ENABLE },
								{ label: "禁用", value: BasicStatus.DISABLE },
							]}
						/>
					</Form.Item>
				</Form>
			</Drawer>

			{/* 代码显示 */}
			<Modal
				title="Java代码示例"
				open={codeVisible}
				onCancel={handleCodeCancel}
				footer={null} // 如果你不需要底部按钮，可以设置为 null
				width={800}
				height={600}
			>
				
				<div style={{ position: 'relative', display: 'inline-block', width: '100%' }}>
					<SyntaxHighlighter language="java" style={docco} showLineNumbers>
						{enumCode || ""}
					</SyntaxHighlighter>
					{/* 浮动按钮 */}
					<Tooltip placement="topLeft" title="复制">
						<IconButton 
							style={{
								position: 'absolute',
								top: '10px',          // 调整按钮到面板的顶部
								right: '10px',        // 调整按钮到面板的右侧
								backgroundColor: '#4CAF50',
								color: 'white',
								border: 'none',
								borderRadius: '5px',
								padding: '5px 10px',
								cursor: 'pointer',
								zIndex: 10,           // 确保按钮在面板之上
							}}
							onClick={() => copyFn(enumCode)}>
								<LucideIcon name="Copy" size={20}/>
						</IconButton>
					</Tooltip>
				</div>
			</Modal>
		</>
	);
}
